from django import forms
from django.contrib.auth.models import User
from django.forms.util import ErrorList

class ErrorList(ErrorList):
    """
    Show errors in DIV HTML tags.
    """
    
    def __unicode__(self):
        return self.as_divs()
    
    def as_divs(self):
        if not self:
            return u''
        
        return u'<div class="errorlist">%s</div>' % ''.join([u'<div class="error">%s</div>' % e for e in self])

class SignUpForm(forms.Form):
    """
    User registration/sign up form.
    """
    
    username = forms.CharField()
    email = forms.EmailField(label=u'E-mail')
    password = forms.CharField(min_length=4, widget=forms.PasswordInput())
    password_confirm = forms.CharField(min_length=4, widget=forms.PasswordInput(), label=u'Password (confirm)')
    
    def clean_username(self):
        """
        Check if user name is unique.
        """
        
        username_data = self.cleaned_data['username']
        
        try:
            User.objects.get(username=username_data)
            raise forms.ValidationError(u'This user name is in use.')
        except User.DoesNotExist:
            return username_data
    
    def clean_email(self):
        """
        Check if email is unique.
        """
        
        email_data = self.cleaned_data['email']
        
        try:
            User.objects.get(email=email_data)
            raise forms.ValidationError(u'This email is in use.')
        except User.DoesNotExist:
            return email_data
    
    def clean_password_confirm(self):
        """
        Check if passwords match.
        """
        
        cleaned_data = self.cleaned_data
        
        password_data = cleaned_data.get('password')
        password_confirm_data = cleaned_data.get('password_confirm')
        
        if password_data != password_confirm_data:
            self._errors['password_confirm'] = ErrorList([u'Enter a matching password.'])
            
            del cleaned_data['password']
            del cleaned_data['password_confirm']
        
        return cleaned_data
